<template>
  <div calss>
    <div id="3d-graph"></div>
  </div>
</template>
<script>
import ForceGraph3D from "3d-force-graph";
import * as THREE from "three";

import getalldata from "./getalldata";
import res from "./aa.js";
import axios from "axios";

export default {
  components: {},
  data() {
    return {
      allres: {},
      Graph: {},
      angle: 0,
      distance: 1700,
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.getalldatas();
    this.initdata();
  },
  methods: {
    async getalldatas() {
      let _this = this;

      let alllist = {
        sys: {
          name: "实验室",
          baseurl: "192.168.1.220:8080",
          username: "cjyw",
          password: "qhlk_2017"
        },
        smx: {
          name: "三门峡",
          baseurl: "39.98.51.253:10303",
          username: "cjyw",
          password: "qhlk_2017"
        },
        liulin: {
          name: "巩登",
          baseurl: "39.98.51.253:10350",
          username: "cjyw",
          password: "qhlk_2017"
        },
        hz: {
          name: "汉中",
          baseurl: "39.98.51.253:10343",
          username: "cloudinnov",
          password: "cloudinnov17"
        },
        xh: {
          name: "西篁",
          baseurl: "39.98.51.253:10183",
          username: "cjyw",
          password: "qhlk_2017"
        },
      };
      let alltoken = {};
      let allres = {};
      _.forIn(alllist, async (item, index) => {
        let loginres = await axios.post(
          `http://${item.baseurl}/itsu/logindo?loginName=${item.username}&loginPassword=${item.password}&language=cn&type=oem`
        );
        if (loginres.data.code == 1) {
          alltoken[index] = { token: loginres.data.token };
          console.log(alltoken);

          allres[index] = { name: item.name, id: index, list: {} };
          let alltunnellist = await axios.get(
            `http://${item.baseurl}/itsu/webapi/section/search?index=1&size=10000&type=tunnel&token=${alltoken[index].token}&language=cn`
          );

          if (alltunnellist.data.code == 1) {
            alltunnellist.data.list.map(async eachtunnelitem => {
              let eachtunneldata = await axios.get(
                `http://${item.baseurl}/itsu/webapi/equipment/selectEquiClassifyAndEquipments?type=tunnel&sectionCode=${eachtunnelitem.code}&token=${alltoken[index].token}&language=cn`
              );
              if (eachtunneldata.data.code == 1) {
                allres[index].list[eachtunnelitem.code] = {
                  name: eachtunnelitem.name,
                  id: eachtunnelitem.code,
                  list: eachtunneldata.data.list
                };
              }
            });
          }
        }
      });

      setTimeout(() => {
        console.log(allres);
        this.allres = allres;
        _this.initdata();
      }, 3000);
    },
    initdata() {

      let _this = this

      //四级节点
      //1.管理员2.隧道所3.隧道4.设备类型5.设备

      //1.管理员节点
      let gData = {
        nodes: [
          { id: 0, group: 1, name: "创杰隧道管理平台", typecode: "guanliyuan" }
        ],
        links: []
      };

      let tunnelg = 10000;
      let typeg = 20000;
      let devg = 30000;

      _.forIn(this.allres, (tunnelsitem, index) => {
        //2.隧道所节点
        gData.nodes.push({
          id: tunnelsitem.id,
          typecode: "tunnels",
          group: 2,
          name: tunnelsitem.name
        });
        gData.links.push({ source: 0, target: tunnelsitem.id });

        //3.隧道节点
        _.forIn(tunnelsitem.list, tunnelitem => {
          gData.nodes.push({
            id: tunnelsitem.id + "|" + tunnelitem.id,
            typecode: "tunnel",
            group: tunnelg,
            name: tunnelitem.name
          });
          gData.links.push({
            source: tunnelsitem.id,
            target: tunnelsitem.id + "|" + tunnelitem.id
          });

          //4.设备分类节点
          tunnelitem.list.map(devtypeitem => {
            gData.nodes.push({
              id:
                tunnelsitem.id +
                "|" +
                tunnelitem.id +
                "|" +
                devtypeitem.categoryCode,
              typecode: devtypeitem.categoryCode,
              group: typeg,
              name: devtypeitem.categoryName
            });
            gData.links.push({
              source: tunnelsitem.id + "|" + tunnelitem.id,
              target:
                tunnelsitem.id +
                "|" +
                tunnelitem.id +
                "|" +
                devtypeitem.categoryCode
            });

            //5.设备节点equipmensInfo
            devtypeitem.equipmensInfo.map(devitem => {
              let res = _this.switchtype(devitem)

              gData.nodes.push({
                type: 'dev',
                id:
                  tunnelsitem.id +
                  "|" +
                  tunnelitem.id +
                  "|" +
                  devtypeitem.categoryCode +
                  "|" +
                  devitem.code,
                typecode: devtypeitem.categoryCode + '-' + res.status,
                group: devg,
                name: devitem.name
              });
              gData.links.push({
                source:
                  tunnelsitem.id +
                  "|" +
                  tunnelitem.id +
                  "|" +
                  devtypeitem.categoryCode,
                target:
                  tunnelsitem.id +
                  "|" +
                  tunnelitem.id +
                  "|" +
                  devtypeitem.categoryCode +
                  "|" +
                  devitem.code
              });
            });
            devg++;
          });
          typeg++;
        });
        tunnelg++;
      });

      console.log(gData);

      // this.allres.list.map(item => {
      //   gData.nodes.push({
      //     id: item.code,
      //     typecode: item.code,
      //     group: typeg,
      //     name: item.categoryName
      //   });
      //   gData.links.push({ source: 0, target: item.code });
      //   item.equipmensInfo.map(item1 => {
      //     gData.nodes.push({
      //       id: item1.code,
      //       group: devg,
      //       name: item1.name,
      //       typecode: item.code
      //     });
      //     gData.links.push({ source: item.code, target: item1.code });
      //   });
      //   typeg++;
      //   devg++;
      // });

      let highlightNodes = [];
      let highlightLink = null;

      let Graph = ForceGraph3D()(document.getElementById("3d-graph"))
        // .nodeAutoColorBy("group")
        // .backgroundColor("#555")
        // .dagMode("td")
        .nodeLabel("name")
        .nodeThreeObject(item => {
          // use a sphere as a drag handle
          const obj = new THREE.Mesh(
            new THREE.SphereGeometry(7),
            new THREE.MeshBasicMaterial({
              depthWrite: false,
              transparent: true,
              opacity: 0
            })
          );

          // add img sprite as child

          let imgpath = ''
          if (_.has(item, 'type')) {
            imgpath = `/img/${item.typecode}.png`
          }else{
            imgpath = `/img/${item.typecode}-3.png`
          }

          const imgTexture = new THREE.TextureLoader().load(
            imgpath
          );
          // imgTexture.premultiplyAlpha = true
          const material = new THREE.SpriteMaterial({ map: imgTexture });
          const sprite = new THREE.Sprite(material);
          sprite.scale.set(20, 20);
          obj.add(sprite);


          return obj;
        })
        .graphData(gData)
        .linkWidth(1)
        .linkOpacity(0.8)
        // .linkDirectionalParticles(link => 5)
        // .linkDirectionalParticleSpeed(d => 0.5)
        .linkAutoColorBy(d => {
          let arrnode = gData.nodes.filter(aaa => {
            return aaa.id == d.source
          })
          return arrnode[0].group
        });

      // .nodeColor(node =>
      //   highlightNodes.indexOf(node) === -1
      //     ? ""
      //     : "rgb(255,0,0,1)"
      // )
      // .linkWidth(link => (link === highlightLink ? 4 : 1))
      // .linkDirectionalParticles(link => (link === highlightLink ? 4 : 0))
      // .linkDirectionalParticleWidth(4)
      // .onNodeHover(node => {
      //   // no state change
      //   if (
      //     (!node && !highlightNodes.length) ||
      //     (highlightNodes.length === 1 && highlightNodes[0] === node)
      //   )
      //     return;

      //   highlightNodes = node ? [node] : [];

      //   updateHighlight();
      // })
      // .onLinkHover(link => {
      //   // no state change
      //   if (highlightLink === link) return;

      //   highlightLink = link;
      //   highlightNodes = link ? [link.source, link.target] : [];

      //   updateHighlight();
      // });

      // let angle = 0;
      // let distance = 1700;
      // setInterval(() => {
      //   // if (false) {
      //     if (true) {
      //       Graph.cameraPosition({
      //         x: distance * Math.sin(angle),
      //       z: distance * Math.cos(angle)
      //     });
      //     angle += 0.01;
      //   }
      // }, 0);

      function updateHighlight() {
        // trigger update of highlighted objects in scene
        Graph.nodeColor(Graph.nodeColor())
          .linkWidth(Graph.linkWidth())
          .linkDirectionalParticles(Graph.linkDirectionalParticles());
      }

      this.Graph = Graph
      this.animate()
    },
    animate() {
      let _this = this
      requestAnimationFrame(function () {
        // if (false) {
          if (true) {
            _this.Graph.cameraPosition({
              x: _this.distance * Math.sin(_this.angle),
            z: _this.distance * Math.cos(_this.angle)
          });
          _this.angle += 0.01;
          if (_this.angle == 360) {
            _this.angle =0
          }
        }
        _this.animate()
        
      })
    },
    switchtype(item) {

      let res = {

      }

      //判断是否为故障状态
      if(item.currentState == 2){
        res.status = -5
        return res
      }

      switch (item.categoryCode) {
        case "JQZMDNZM":
        case "JBZMDNZM":
        case "YDZMDNZM":
          if (item.currentState != -1 && item.indexType.FEEDBACK != '0') {
            res.status = item.indexType.FEEDBACK == "1" ? 3 : 0;
          } else {
            res.status = -1;
          }
          break;
          //交通信号灯 {LEFT: "0", HL: "0", HR: "0", FAULT: "1", HG: "0"}
        case "JTXHD":
          if (item.currentState != -1 && item.indexType.FEEDBACK != '0') {
            switch (item.indexType.FEEDBACK) {
              case "1":
                res.status = 1;
                break;
              case "2":
                res.status = 2;
                break;
              case "4":
                res.status = 4;
                break;
              case "8":
                res.status = 8;
                break;
              default:
                break;
            }
          } else {
              res.status = -1;
          }
            break;
          case "CDZSQ":
          case "DZZCDZSQ":
              if (item.currentState != -1 && item.indexType.FEEDBACK != '0') {
                  if (!item.equipmentsAttr) {
                      res.status = -1;
                      break;
                  }

                  let direction = item.equipmentsAttr.filter(item => {
                      return item.value == "left";
                  });

                  if (direction.length == 1) {
                      switch (item.indexType.FEEDBACK) {
                          case "1":
                              res.status = "0-1";
                              break;
                          case "2":
                              res.status = "1-0";
                              break;
                          case "4":
                              res.status = "0-0";
                              break;
                          case "8":
                              res.status = "1-1";
                              break;
                          case "16":
                              res.status = "0-21";
                              break;

                          default:
                              break;
                      }
                  } else {
                      switch (item.indexType.FEEDBACK) {
                          case "1":
                              res.status = "1-0";
                              break;
                          case "2":
                              res.status = "0-1";
                              break;
                          case "4":
                              res.status = "0-0";
                              break;
                          case "8":
                              res.status = "1-1";
                              break;
                          case "16":
                              res.status = "2-0";
                              break;

                          default:
                              break;
                      }
                  }
              } else {
                  res.status = -1;
              }
              break;
          case "SDFJ":
              if (item.currentState != -1 && item.indexType.FEEDBACK != '0') {
                  res.status =
                      item.indexType.FEEDBACK == "1" ?
                          1 :
                          item.indexType.FEEDBACK == "2" ?
                              2 :
                              0;
              } else {
                  res.status = -1;
              }
              break;

            case "HDJIM":
              if (item.currentState != -1 && item.indexType.FEEDBACK != '0') {
                  res.status =
                      item.indexType.FEEDBACK == "1" ?
                          1 :
                          item.indexType.FEEDBACK == "2" ?
                              2 :
              3;
          } else {
            res.status = -1;
          }
          break;
        case "GDWSC":
          if (item.currentState != -1) {
            res.status = item.indexType.GWSC ? "G" : "D";
          } else {
            res.status = -1;
          }
          break;

        default:
          if (item.currentState != -1) {
            res.status = 3;
          } else {
            res.status = -1;
          }
          break;
      }

      return res
    },
  }
};
</script>
<style lang='scss' scoped>
</style>